<?php
/**
 * Created by PhpStorm.
 * User: HUNG NGUYEN
 * Date: 3/19/14
 * Time: 11:02 AM
 */

class ShopController extends BaseController {

    public function postRegister()
    {            
        try{
            $input=Input::json()->all();

            $user_id=InputHelper::getInput($input,'user_id');

            $name=InputHelper::getInput($input,'name');

            $address=InputHelper::getInput($input,'address');

            $phone=InputHelper::getInput($input,'phone','');

            $website=InputHelper::getInput($input,'website','');

            if(!empty($website) && !filter_var($website, FILTER_VALIDATE_URL))
            {
                return ErrorResponse::SendErrorMessage('website address invalid');
            }

        }
        catch(Exception $e)
        {
            return ErrorResponse::SendErrorMessage($e->getMessage());
        }
        // insert to database
        try{
            // check shop name
            if(Shops::ShopNameisExist($name))
            {
                return ErrorResponse::SendErrorMessage('Shop name already existed');
            }
            if(Shops::Insert($name,$address,$phone,$website,''))
            {
                $shop_id = Shops::getShopId($name);
                if($shop_id!=-1)
                {
                    return Response::json(array('status'=>'success','id'=>$shop_id));
                }
            }
        }
        catch(Exception $e)
        {
            return ErrorResponse::SendErrorMessage($e->getMessage());
        }
    }

    
    
    public function postEdit()
    {
        try
        {
            $input=Input::json();

            $shop_id=InputHelper::getInput($input,'id',null);

            $user_id=InputHelper::getInput($input,'user_id',null);

            $name=InputHelper::getInput($input,'name',null);

            $address=InputHelper::getInput($input,'address',null);

            $phone=InputHelper::getInput($input,'phone','');

            $website=InputHelper::getInput($input,'website','');

            if(!empty($website) && !filter_var($website, FILTER_VALIDATE_URL))
            {
                return ErrorResponse::SendErrorMessage('website address invalid');
            }
        }
        catch(Exception $e)
        {
            return ErrorResponse::SendErrorMessage($e->getMessage());
        }
        // update to database
        try
        {
            if(Shops::shopIdisExist($shop_id))
            {
                if(Shops::Edit($name,$address,$phone,$website,'',$shop_id))
                {
                    return Response::json(array('status'=>'success'));
                }
            }
        }
        catch(Exception $e)
        {
            return ErrorResponse::SendErrorMessage($e->getMessage());
        }
    }            
} 